package com.pangu.web.handler.api.agentuser;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.pangu.core.BMDataContext;
import com.pangu.core.cache.CacheConfigTools;
import com.pangu.core.cache.CacheHelper;
import com.pangu.util.GameUtils;
import com.pangu.util.disruptor.DisruptorHandler;
import com.pangu.util.rules.model.ClientGameConfig;
import com.pangu.util.rules.model.RespCode;
import com.pangu.util.rules.model.RespEntity;
import com.pangu.web.model.AiConfig;
import com.pangu.web.model.GameConfig;
import com.pangu.web.model.Notice;
import com.pangu.web.model.PlayUser;
import com.pangu.web.model.PlayUserClient;
import com.pangu.web.model.SysGameConfig;
import com.pangu.web.model.Token;
import com.pangu.web.model.UserQuestion;
import com.pangu.web.service.repository.es.PlayUserClientESRepository;
import com.pangu.web.service.repository.es.PlayUserESRepository;
import com.pangu.web.service.repository.es.TokenESRepository;
import com.pangu.web.service.repository.jpa.NoticeRepository;
import com.pangu.web.service.repository.jpa.PlayUserRepository;
import com.pangu.web.service.repository.jpa.UserQuestionRepository;

import lombok.extern.slf4j.Slf4j;
@RestController
@RequestMapping("/api/agent")
@CrossOrigin
public class AgentSystemController{
	@Autowired
	private PlayUserClientESRepository playUserClientESRes ;
	@Autowired
	private TokenESRepository tokenESRes ;
	@Autowired
	private PlayUserRepository playUserRes ;
	@Autowired
	private UserQuestionRepository userQuestionRepository ;
	@Autowired
	private NoticeRepository noticeRepository ;
	@Autowired
	private PlayUserESRepository playUserESRes;
	
	//登录（游戏H5端发起）
	@PostMapping("/login")
    public RespEntity login(HttpServletRequest request) {
		String token=request.getHeader(BMDataContext.AUTHORIZATION);
		Token userToken = tokenESRes.findById(token) ;
		if(userToken!=null&&userToken.getExptime().after(new Date())) {
			try {
				PlayUserClient playUserClient=playUserClientESRes.findById(userToken.getUserid());//先从ES中查询
				if(playUserClient==null){
					PlayUser playuser=playUserRes.findById(userToken.getUserid());
					if(playuser!=null) {
						playUserClient=new PlayUserClient();
						BeanUtils.copyProperties(playUserClient , playuser);
					}
				}
				if(playUserClient!=null){
					JSONObject resobj=new JSONObject();
					resobj.put(BMDataContext.PLAYUSERCLIENT, playUserClient);
					
					CacheHelper.getApiUserCacheBean().put(userToken.getId(),userToken, userToken.getOrgi());
					CacheHelper.getApiUserCacheBean().put(playUserClient.getId(),playUserClient, userToken.getOrgi());
					
					ClientGameConfig clientGameConfig = new ClientGameConfig() ;
					SysGameConfig gameConfig = CacheConfigTools.getSysGameConfig(userToken.getOrgi()) ;
					if(gameConfig!=null){
						clientGameConfig.setGametype("hall");//大厅模式
						clientGameConfig.setNoaiwaitime(gameConfig.getTimeout());	//无AI的时候 等待时长
						clientGameConfig.setNoaimsg(gameConfig.getTimeoutmsg());    //无AI的时候，到达最大时长以后的 提示消息，提示完毕后，解散房间
						clientGameConfig.setRecmsg(gameConfig.getRecmsg());
						clientGameConfig.setGames(GameUtils.gamesNew(gameConfig.getGametype()));//找到游戏配置的 模式 和玩法，如果多选，则默认进入的是 大厅模式，如果是单选，则进入的是选场模式
						clientGameConfig.setEnableai(true);
						clientGameConfig.setWaittime(gameConfig.getTimeout());
					}
					resobj.put(BMDataContext.CLIENTGAMECONFIG, clientGameConfig);
					return new RespEntity(RespCode.R0000,resobj);//根据游戏配置 ， 选择 返回的 玩法列表
				}else{
					return new RespEntity(RespCode.R1006);
				}
			} catch (Exception e) {
				e.printStackTrace();
				return new RespEntity(RespCode.R9999);
			}
		}else {
			return new RespEntity(RespCode.R1007);
		}
	}
	
	//用户信息修改（游戏H5端发起）
	@PostMapping("/updateUserInfo")
    public RespEntity updateUserInfo(@RequestBody JSONObject reqobj) {
		PlayUser playuser=playUserRes.findById(reqobj.getString("userid"));
		try {
			if(playuser!=null) {
				if(reqobj.getString("nickname")!=null) {
					playuser.setNickname(reqobj.getString("nickname"));
				}
				if(reqobj.getString("headimgaddr")!=null) {
					playuser.setHeadimgaddr(reqobj.getString("headimgaddr"));
				}
				DisruptorHandler.published(playuser , playUserESRes , playUserRes);
				//更新缓存
				PlayUserClient playUserClient=new PlayUserClient();
				BeanUtils.copyProperties(playUserClient , playuser);
				CacheHelper.getApiUserCacheBean().put(playUserClient.getId(),playUserClient, playUserClient.getOrgi());
				return new RespEntity(RespCode.R0000);
			}else {
				return new RespEntity(RespCode.R1006);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new RespEntity(RespCode.R9999);
		}
	}
	
	//问题反馈（游戏H5端发起）
	@PostMapping("/sumbitUserQuestion")
    public RespEntity sumbitUserQuestion(@RequestBody UserQuestion userquestion) {
		PlayUser playuser=playUserESRes.findById(userquestion.getUserid());
		try {
			if(playuser!=null) {
				userQuestionRepository.save(userquestion);
				return new RespEntity(RespCode.R0000);
			}else {
				return new RespEntity(RespCode.R1006);
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new RespEntity(RespCode.R9999);
		}
	}
	
	//公告列表获取
	@PostMapping("/getNoticList")
    public RespEntity getNoticList(@RequestBody JSONObject reqobj) {
		Sort sort = new Sort(Direction.DESC, "createtime");
		List<Notice> noticlist=noticeRepository.findFirst10ByUseridIsNullOrUserid(reqobj.getString("userid"),sort);
		return new RespEntity(RespCode.R0000,noticlist);
	}
	
	//公告列表获取
	@PostMapping("/updateNoticStatus")
    public RespEntity updateNoticStatus(@RequestBody JSONObject reqobj) {
		try {
			if(!StringUtils.isBlank(reqobj.getString("ids"))){
				String ids=reqobj.getString("ids");
				String[] arry=ids.split(",");
				for(String id:arry) {
					noticeRepository.updateStatusById("1", id);
				}
			}
			return new RespEntity(RespCode.R0000);
		} catch (Exception e) {
			e.printStackTrace();
			return new RespEntity(RespCode.R9999);
		}
	}
	
}